//== 流程接口
let EWorkFlow = function () {
    // 以下为模态框id
    /**
     * 表单
     * @type {string}
     */
    let MODAL_FORM = "modal-work-flow-form";
    /**
     * 流程进度
     * @type {string}
     */
    let MODAL_TRACE = "modal-work-flow-trace";

    /**
     * 撤销申请
     * @type {string}
     */
    let REVOKE = "modal-revoke";

    // 工作流根url
    let workFlowBaseUrl = basePath + '/auth/activiti/process/definition/';

    /**
     * 格式化耗时
     *
     * @param duration {number} 耗时
     * @return {*} n秒、n分钟、n小时...
     */
    let durationFormat = function (duration) {
        if (duration < 1000) {
            return '0秒';
        }
        if (1000 < duration && duration < 1000 * 60) {
            return (duration / 1000).toFixed(0) + '秒';
        }
        if (1000 * 60 < duration && duration < 1000 * 60 * 60) {
            return (duration / 1000 / 60).toFixed(0) + '分钟';
        }
        if (1000 * 60 * 60 < duration && duration < 1000 * 60 * 60 * 24) {
            return (duration / 1000 / 60 / 60).toFixed(1) + '小时';
        }
        if (1000 * 60 * 60 * 24 < duration) {
            return (duration / 1000 / 60 / 60 / 24).toFixed(1) + '天';
        }
    };

    /**
     * 生成模态框
     * @param modalId {string} 模态框id
     * @param title {string} 模态框标题
     * @param size {string} 尺寸 eg: sm/md/lg/xl，默认为md
     * @return {element}
     */
    let generateHasWorkFlowModal = function (modalId, title, size) {
        let $modal = $('#' + modalId);
        if (!$modal.length) {
            // 没有模态框，添加
            $modal = $('\
                <div class="modal fade" id="' + modalId + '" role="dialog" aria-modal="true">\
                    <div class="modal-dialog" role="document">\
                        <div class="modal-content">\
                            <div class="modal-header">\
                                <h5 class="modal-title">' + title + '</h5>\
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close"></button>\
                            </div>\
                            <div class="modal-body"></div>\
                        </div>\
                    </div>\
                </div>');
            $('body').append($modal);
        }
        if (EUtil.isNotBlank(size)) {
            $modal.find('.modal-dialog').removeClass().addClass('modal-dialog modal-' + size);
        }
        return $modal;
    };

    /**
     * 撤销申请
     *
     * @param processInstanceId {string} 流程实例ID
     * @param deleteReason {string|null} 撤销原因(可为空)
     */
    let revoke = function (processInstanceId, deleteReason) {
        EUtil.ajax({
            url: basePath + '/auth/activiti/task/revoke/' + processInstanceId,
            data: {
                deleteReason: deleteReason
            },
            success: function (res) {
                ETool.successTip(commonTips.success, '申请已撤销');
                // 检查有没有撤销申请的模态框，如果有则关闭
                let $modal = $('#' + REVOKE);
                if($modal.length){
                    $modal.modal('hide');
                }
                // 检查有没有表格，如果有则刷新
                if($('.e-datatable').length){
                    $('.btn-search').click();
                }
            }
        });
    }

    return {
        /**
         * 加载流程历史活动记录
         *
         * @param processInstanceId {string} 流程实例ID
         * @param $content {object} 容器
         */
        loadHistoric: function (processInstanceId, $content) {
            EUtil.ajax({
                url: basePath + '/auth/activiti/historic/select',
                data: {
                    processInstanceId: processInstanceId
                },
                success: function (res) {
                    let $table = $('\
                        <table class="table" id="historic-table">\
                            <thead>\
                            <tr>\
                                <th>#</th>\
                                <th>活动ID</th>\
                                <th>活动名称</th>\
                                <th>活动类型</th>\
                                <th>任务ID</th>\
                                <th>办理人</th>\
                                <th>开始时间</th>\
                                <th>结束时间</th>\
                                <th>耗时</th>\
                            </tr>\
                            </thead>\
                            <tbody></tbody>\
                        </table>\
                    ');
                    $(res.data).each(function (index, data) {
                        if ('exclusiveGateway' !== data.activityType) {
                            $table.append('\
                                <tr>\
                                    <td>' + (index + 1) + '</td>\
                                    <td>' + data.id + '</td>\
                                    <td>' + (data.activityName ? data.activityName : '-') + '</td>\
                                    <td>' + ETool.getDictElement(data.activityType, ETool.getSysDictsObjectByDictType('activityType')) + '</td>\
                                    <td>' + (data.taskId ? data.taskId : '-') + '</td>\
                                    <td>' + (data.assignee ? data.assignee : '-') + '</td>\
                                    <td>' + data.startTime + '</td>\
                                    <td>' + (data.endTime ? data.endTime : '-') + '</td>\
                                    <td>' + (data.duration ? durationFormat(data.duration) : '-') + '</td>\
                                </tr>\
                            ');
                        }
                    });
                    $content.append($table);
                }
            });
        },

        /**
         * 加载相关变量
         *
         * @param processInstanceId {string} 流程实例ID
         * @param $content {object} 容器
         */
        loadVariable: function (processInstanceId, $content) {
            EUtil.ajax({
                url: basePath + '/auth/activiti/variable/select',
                data: {
                    processInstanceId: processInstanceId
                },
                success: function (res) {
                    let $table = $('\
                        <table class="table">\
                            <thead>\
                            <tr>\
                                <th>#</th>\
                                <th>变量名称</th>\
                                <th>变量类型</th>\
                                <th>值</th>\
                                <th>创建时间</th>\
                                <th>最后更新时间</th>\
                            </tr>\
                            </thead>\
                            <tbody></tbody>\
                        </table>\
                    ');
                    $(res.data).each(function (index, data) {
                        $table.append('\
                            <tr>\
                                <td>' + (index + 1) + '</td>\
                                <td>' + data.name + '</td>\
                                <td>' + data.variableTypeName + '</td>\
                                <td><span class="e-ell" title="' + data.textValue + '"></span>' + data.textValue + '</td>\
                                <td>' + data.createTime + '</td>\
                                <td>' + data.lastUpdatedTime + '</td>\
                            </tr>\
                        ');
                    });
                    $content.append($table);
                }
            });
        },

        /**
         * 尝试启动流程
         *（先验证有无动态表单，如果没有自动提交返回流水号，如果有打开表单模态框）
         *
         * @param key {string} 模型标识
         * @param businessKey {string} 业务数据ID
         * @param businessTitle {string} 业务名称
         * @param businessDetailsUrl {string} 业务详情url
         * @param extentParams {string} 扩展参数(注意此参数必须是JSON格式)
         */
        attemptStartProcessInstance: function (key, businessKey, businessTitle, businessDetailsUrl, extentParams) {
            // 检查流程状态
            EUtil.ajax({
                url: basePath + '/auth/activiti/model/select/process/definition/id/' + key,
                success: function (res) {
                    EUtil.ajax({
                        async: false,
                        needAlert: false,
                        url: workFlowBaseUrl + 'attempt/start/process/instance/' + res.data,
                        data: {
                            businessKey: businessKey,
                            businessTitle: businessTitle,
                            businessDetailsUrl: businessDetailsUrl,
                            extentParams: extentParams
                        },
                        success: function (res) {
                            if (res.data.hasStartForm) {
                                // 有动态表单，打开模态框填写
                                let $modal = generateHasWorkFlowModal(MODAL_FORM, '发起流程', 'md');
                                let url = workFlowBaseUrl + res.data.url + '?businessKey=' + businessKey + '&businessTitle=' + businessTitle;
                                $modal.find('.modal-body').html(
                                    '<iframe src="' + url + '" frameborder="0" class="page-frame" style="width: 100%;height: 300px;overflow-x: hidden"></iframe>'
                                );
                                $modal.modal();
                            } else {
                                ETool.successTip(commonTips.success, '流程已启动，实例ID：' + res.data.processInstanceId);
                            }
                        }
                    });
                }
            });
        },
        /**
         * 更新详情页面高度
         */
        updateDetailsPageLayout: function () {
            let height = $('.e-content').outerHeight();
            $('#businessDetails', window.parent.document).height(height);
        },
        /**
         * 根据业务数据id打开流程跟踪模态框
         *
         * @param businessKey {string} 业务数据id
         */
        openProcessProgressWithBusinessKey: function (businessKey) {
            EUtil.ajax({
                url: basePath + '/auth/activiti/historic/select/task/' + businessKey,
                success: function (res) {
                    if (EUtil.isNotBlank(res.data.processInstanceId) && EUtil.isNotBlank(res.data.executionId)) {
                        EWorkFlow.openProcessProgress(res.data.executionId, res.data.processInstanceId);
                    } else {
                        ETool.warnTip(commonTips.fail, '未查询到流程信息');
                    }
                }
            });
        },
        /**
         * 打开流程跟踪模态框
         * @param executionId {string} 执行实例ID
         * @param processInstanceId {string} 流程实例ID
         */
        openProcessProgress: function (executionId, processInstanceId) {
            let $modal = generateHasWorkFlowModal(MODAL_TRACE, '流程跟踪', 'xl');
            $modal.find('.modal-body').html(
                '<div class="e-section e-section--last select-flow-chart">\
                    <h3 class="e-section-title">\
                        审核进度\
                    </h3>\
                    <div class="e-section-content">\
                        <img class="e-block-center" style="display: block;width: 70%;height: auto;" src="' + basePath + '/auth/activiti/process/trace/process/progress/image/' + executionId + '">\
                    </div>\
                    <div class="e-separator e-separator--dashed"></div>\
                </div>\
                <div class="e-section e-section--last">\
                    <h3 class="e-section-title">\
                        流程历史活动记录\
                    </h3>\
                    <div class="e-section-content historic-section"></div>\
                    <div class="e-separator e-separator--dashed"></div>\
                </div>\
                <!-- 管理员查阅 -->\
                <div class="e-section e-section--last section-variable e-hide">\
                    <h3 class="e-section-title">\
                        相关变量\
                    </h3>\
                    <div class="e-section-content variable-section"></div>\
                </div>'
            );
            EWorkFlow.loadHistoric(processInstanceId, $modal.find('.historic-section'));

            if (ETool.hasRole('sys:admin')) {
                // 如果是系统管理员显示相关变量
                let $content = $modal.find('.variable-section');
                $content.parent().removeClass('e-hide');
                EWorkFlow.loadVariable(processInstanceId, $content);
            }
            $modal.modal();
        },
        /**
         * 撤销申请
         *
         * @param processInstanceId {string} 流程实例ID
         * @param deleteReason {string|null} 撤销原因(可为空)
         */
        revoke: function (processInstanceId, deleteReason) {
            revoke(processInstanceId, deleteReason);
        },
        /**
         * 撤销申请
         *
         * @param processInstanceId {string} 流程实例ID
         */
        revokeWithReason: function (processInstanceId) {
            let $modal = generateHasWorkFlowModal(REVOKE, '撤销申请', 'sm');
            $modal.find('.modal-body').html(
                '<textarea name="deleteReason" class="form-control" data-process-instance-id="' + processInstanceId + '" placeholder="请输入撤销申请原因"></textarea>'
            );
            if(!$modal.find('.modal-footer').length){
                $modal.find('.modal-content').append('\
                    <div class="modal-footer">\
                        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>\
                        <button type="button" class="btn btn-brand btn-revoke">确定</button>\
                    </div>'
                );
            }

            $modal.modal('show');
            $modal.find('.btn-revoke').off('click').click(function () {
                let $textarea = $modal.find('[name="deleteReason"]');
                EWorkFlow.revoke($textarea.data('process-instance-id'), $textarea.val());
            });
        }
    }
}();